package main

import (
	"context"
	"flag"
	"log"
	"os"
	"time"

	"github.com/olivere/elastic/v7"
)

/**
* Author: dinglin
* Date: 2021/8/31 10:32 上午
 */

func doRestore() {
	if config.toHost == "" {
		log.Printf("toHost miss")
		flag.PrintDefaults()
		os.Exit(-1)
	}
	if config.repository == "" || config.toIndex == "" || config.snapshotName == "" {
		log.Printf("repository or to_index miss")
		flag.PrintDefaults()
		os.Exit(-1)
	}
	from, err := NewEsClient(config.toHost)
	if err != nil {
		os.Exit(-1)
	}
	err = restore(from, config.toHost, config.repository, config.snapshotName, config.toIndex)
	if err != nil {
		os.Exit(-1)
	}
}

func restore(client *elastic.Client, esHost, repository, snapshotName, index string) error {
	log.Printf("start snapshot restore %s ---> %s", snapshotName, index)
	service := client.SnapshotRestore(repository, snapshotName).WaitForCompletion(false)
	service.MasterTimeout("1d").IndexSettings(map[string]interface{}{
		"index.number_of_replicas": 0,
	})
	resp, err := service.Indices(index).Do(context.Background())
	if err != nil {
		log.Printf("restore %s: %v", snapshotName, err)
		return err
	}
	log.Print("wait restore complete")
	waitGreen(client)
	for range time.Tick(time.Minute) {
		cnt, _ := waitRecovery(esHost, index)
		if cnt == 0 {
			break
		}
	}
	log.Printf("complete snapshot restore %s %s", index, print(resp))
	indexRefresh(client, index)
	return nil
}
